home *** CD-ROM | disk | FTP | other *** search
- Path: keats.ugrad.cs.ubc.ca!not-for-mail
- From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
- Newsgroups: comp.lang.c
- Subject: Re: Sort Function
- Date: 1 Apr 1996 11:39:24 -0800
- Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
- Message-ID: <4jpbdcINN16c@keats.ugrad.cs.ubc.ca>
- References: <4jmq99$cqi@freenet-news.carleton.ca>
- NNTP-Posting-Host: keats.ugrad.cs.ubc.ca
-
- In article <4jmq99$cqi@freenet-news.carleton.ca>,
- Jerry Boyd <aq436@FreeNet.Carleton.CA> wrote:
- >
- >
- >How would I WRITE a function (called sort3) that would
- >sort three integers (in assending order) by using pointers
- >and NOT arrays?
-
- That would be blatantly inefficient. You can't count on the implementation to
- inline trivial functions. A comma-expression macro is called for:
-
- #define SWP(x,y,tmp) ((tmp) = (x), (x) = (y), y = (tmp))
- #define CSW(x,y,tmp) ((x) > (y) ? SWP(x,y,tmp) : (tmp = tmp))
- #define sort3(a, b, c, tmp) (CSW(a,b,tmp), CSW(b,c,tmp), CSW(a,b,tmp))
-
- /*
- * The drawback is that the client of sort3() has to provide temporary storage
- * in the form of a fourth parameter. But the nice thing is that this will work
- * on integral, floating-point and pointer types alike!
- */
-
- #include <stdio.h>
-
- int main(int argc, char **argv)
-
- {
- int a, b, c, tmp;
-
- printf("enter three integers to be sorted: ");
-
- scanf("%d%d%d",&a,&b,&c);
-
- sort3(a,b,c,tmp);
-
- printf("your integers are: %d, %d, %d\n",a,b,c);
-
- return 0;
- }
-
- The superflous (tmp = tmp) expression is required to supply the syntactic
- requirements of the conditional statement: the expressions are not optional
- like for example in for(;;).
-
- Of course, I'm counting on the implementation to optimize away a useless
- assignment... :)
- --
-
-